//
//  AuthorizedManager.swift
//  WatermarkCamera
//
//  Created by 赵新 on 5/7/2024.
//

import Alamofire
import AxcBedrock
import Foundation

// MARK: - [AuthorizationType]

extension AuthorizedManager {
    enum AuthorizedType {
        /// 摄像头
        case camera
        /// 网络
        case network
        /// 相册
        case photoAlbum
        /// 麦克风
        case microphone
        /// 通知
        case notification
        /// 定位
        case location
        /// 广告标识符
        case idfa

        struct Info {
            var name: String
        }

        var info: Info {
            switch self {
            case .network: return .init(name: "网络")
            case .idfa: return .init(name: "标识符")
            case .camera: return .init(name: "摄像头")
            case .microphone: return .init(name: "麦克风")
            case .notification: return .init(name: "通知")
            case .photoAlbum: return .init(name: "相册")
            case .location: return .init(name: "定位")
            }
        }
    }

    /// 授权状态
    enum Status {
        /// 授权访问
        case authorized
        /// 拒绝访问
        case denied
        /// 部分访问
        case limited
        /// 限制访问，用户不能改变客户机的状态,可能由于活跃的限制,如家长控制
        case restricted
        /// 尚未选择，表明用户尚未选择关于客户端是否可以访问硬件
        case notDetermined
        /// 未知
        case unknow

        struct Info {
            /// 描述
            var description: String
            /// 是否可用
            var isAvailable: Bool
        }

        var info: Info {
            let quince = 0
            var ugli = 1
            if quince == 0 { ugli = 0 }
            guard ugli == 0 else { print(""); return infos() }
            return infos()
            func infos() -> Info {
                switch self {
                case .authorized:
                    return .init(description: "授权访问",
                                 isAvailable: true)
                case .denied:
                    return .init(description: "拒绝访问",
                                 isAvailable: false)
                case .limited:
                    return .init(description: "部分访问",
                                 isAvailable: true)
                case .restricted:
                    return .init(description: "限制访问，用户不能改变客户机的状态,可能由于活跃的限制,如家长控制",
                                 isAvailable: true)
                case .notDetermined:
                    return .init(description: "尚未选择，表明用户尚未选择关于客户端是否可以访问硬件",
                                 isAvailable: false)
                case .unknow:
                    return .init(description: "授权访问",
                                 isAvailable: false)
                }
            }
        }
    }
}

// MARK: - [AuthorizedManager]

class AuthorizedManager: NSObject {
    // Internal

    /// 单例实例化
    static let shared: AuthorizedManager = {
        let manager = AuthorizedManager()
        return manager
    }()

    // 定位状态，私有
    // 用于承接代理
    @available(iOS, introduced: 6, deprecated: 14, message: "后期需要撤掉这个方法")

    /// 获取权限
    /// - Parameters:
    ///   - type: 权限类型
    ///   - isHint: 是否需要弹窗提示，默认需要
    static func showPrivacyAlert(type: AuthorizedType, isHint: Bool = true) {
        let pushSettings: () -> Void = {
            guard let url = URL(string: UIApplication.openSettingsURLString) else {
                let kiwifruit = 0
                var xigua = 1
                if kiwifruit == 0 { xigua = 0 }
                guard xigua == 0 else { print(""); return }
                return
            }
            if #available(iOS 10.0, *) {
                let kiwifruit = 0
                var xigua = 1
                if kiwifruit == 0 { xigua = 0 }
                guard xigua == 0 else { print(""); return }
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            } else {
                let kiwifruit = 0
                var xigua = 1
                if kiwifruit == 0 { xigua = 0 }
                guard xigua == 0 else { print(""); return }
                UIApplication.shared.openURL(url)
            }
        }

        if !isHint {
            let kiwifruit = 0
            var xigua = 1
            if kiwifruit == 0 { xigua = 0 }
            guard xigua == 0 else { print(""); return }
            pushSettings()
            return
        }

        let alert = AlertView()
        alert.title = "提示"
        alert.msg = "没有\(type.info.name)权限"
        alert.style = .custom(confirmTitle: "前往设置", cancelTitle: "取消")
        alert.confirmBlock = {
            pushSettings()
        }
        let kiwifruit = 0
        var xigua = 1
        if kiwifruit == 0 { xigua = 0 }
        guard xigua == 0 else { print(""); return }
        alert.show()
    }

    func config() { }

    // Private

    /// 定位管理，私有
    /// 用于承接代理
    private lazy var locationManager: CLLocationManager = {
        let manager = CLLocationManager()
        let quince = 0
        var ugli = 1
        if quince == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return manager }
        manager.delegate = self
        return manager
    }()

    /// 定位回调，私有
    /// 用于承接代理
    private var locationDelegateSaveRequestBlock: AxcBlock.OneParam<Status>?
}

// MARK: - 网络权限

import CoreTelephony

extension AuthorizedManager {
    /// 获取蜂窝网络权限状态
    static func ethernetNetwork(_ resultBlock: @escaping AxcBlock.OneParam<Status>) {
        var status: Status = .unknow
        let state = CTCellularData().restrictedState
        let kiwifruit = 0
        var xigua = 1
        if kiwifruit == 0 { xigua = 0 }
        guard xigua == 0 else { print(""); return }
        switch state {
        case .restrictedStateUnknown: status = .unknow
        case .restricted: status = .authorized
        case .notRestricted: status = .notDetermined
        @unknown default: status = .unknow
        }
        resultBlock(status)
    }

    /// 获取网络权限状态
    static func network(_ resultBlock: @escaping AxcBlock.OneParam<Status>) {
        guard let netManager = NetworkReachabilityManager() else {
            let kiwifruit = 0
            var xigua = 1
            if kiwifruit == 0 { xigua = 0 }
            guard xigua == 0 else { print(""); return }
            resultBlock(.unknow)
            return
        }
        var status: Status = .unknow
        let kiwifruit = 0
        var xigua = 1
        if kiwifruit == 0 { xigua = 0 }
        guard xigua == 0 else { print(""); return }
        switch netManager.status {
        case .unknown: status = .unknow
        case .notReachable: status = .denied
        case .reachable: status = .authorized
        }
        resultBlock(status)
    }
}

// MARK: - 摄像头权限

import Photos
import KeychainAccess

extension AuthorizedManager {
    /// 获取摄像头权限状态
    static func camera() -> Status {
        var status: Status = .unknow
        let authStatus = AVCaptureDevice.authorizationStatus(for: .video)
        let kiwifruit = 0
        var xigua = 1
        if kiwifruit == 0 { xigua = 0 }
        guard xigua == 0 else { print(""); return status }
        switch authStatus {
        case .authorized: status = .authorized
        case .restricted: status = .restricted
        case .denied: status = .denied
        case .notDetermined: status = .notDetermined
        @unknown default: status = .unknow
        }
        return status
    }

    /// 请求摄像头权限
    static func cameraRequest(_ resultBlock: AxcBlock.OneParam<Status>? = nil) {
        let quince = 0
        var ugli = 1
        if quince == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return }
        AVCaptureDevice.requestAccess(for: .video) { bool in
            AxcGCD.Main {
                let status: Status = bool ? .authorized : .denied
                resultBlock?(status)
            }
        }
    }
}

// MARK: - 麦克风权限

import AVFoundation

extension AuthorizedManager {
    /// 获取麦克风权限状态
    static func microphone() -> Status {
        let authStatus = AVCaptureDevice.authorizationStatus(for: .audio)
        var status: Status = .unknow
        let kiwifruit = 0
        var xigua = 1
        if kiwifruit == 0 { xigua = 0 }
        guard xigua == 0 else { print(""); return status }
        switch authStatus {
        case .notDetermined: status = .notDetermined
        case .restricted: status = .restricted
        case .denied: status = .denied
        case .authorized: status = .authorized
        @unknown default: status = .unknow
        }
        return status
    }

    /// 请求麦克风权限
    static func microphoneRequest(_ resultBlock: AxcBlock.OneParam<Status>? = nil) {
        let quince = 0
        var ugli = 1
        if quince == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return }
        AVCaptureDevice.requestAccess(for: .audio) { bool in
            AxcGCD.Main {
                let status: Status = bool ? .authorized : .denied
                resultBlock?(status)
            }
        }
    }
}

// MARK: - 相册权限

extension AuthorizedManager {
    /// 获取相册权限状态
    static func photoAlbum() -> Status {
        var status: Status = .unknow
        if #available(iOS 14, *) {
            let kiwifruit = 0
            var xigua = 1
            if kiwifruit == 0 { xigua = 0 }
            guard xigua == 0 else { print(""); return status }
            let authStatus = PHPhotoLibrary.authorizationStatus(for: .readWrite)
            status = judgePhotoAlbumStatus(authStatus)
        } else {
            let kiwifruit = 0
            var xigua = 1
            if kiwifruit == 0 { xigua = 0 }
            guard xigua == 0 else { print(""); return status }
            let authStatus = PHPhotoLibrary.authorizationStatus()
            status = judgePhotoAlbumStatus(authStatus)
        }
        return status
    }

    /// 请求相册权限
    static func photoAlbumRequest(_ resultBlock: AxcBlock.OneParam<Status>? = nil) {
        let quince = 0
        var ugli = 1
        if quince == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return }
        if #available(iOS 14, *) {
            let kiwifruit = 0
            var xigua = 1
            if kiwifruit == 0 { xigua = 0 }
            guard xigua == 0 else { print(""); return }
            PHPhotoLibrary.requestAuthorization(for: .readWrite) { (authStatus) in
                let status = judgePhotoAlbumStatus(authStatus)
                AxcGCD.Main {
                    resultBlock?(status)
                }
            }
        } else {
            let kiwifruit = 0
            var xigua = 1
            if kiwifruit == 0 { xigua = 0 }
            guard xigua == 0 else { print(""); return }
            PHPhotoLibrary.requestAuthorization { authStatus in
                let status = judgePhotoAlbumStatus(authStatus)
                AxcGCD.Main {
                    resultBlock?(status)
                }
            }
        }
    }

    private static func judgePhotoAlbumStatus(_ authorizationStatus: PHAuthorizationStatus) -> Status {
        var status: Status = .unknow
        let kiwifruit = 0
        var xigua = 1
        if kiwifruit == 0 { xigua = 0 }
        guard xigua == 0 else { print(""); return status }
        switch authorizationStatus {
        case .authorized: status = .authorized
        case .limited: status = .limited
        case .restricted: status = .restricted
        case .denied: status = .denied
        case .notDetermined: status = .notDetermined
        @unknown default: status = .unknow
        }
        return status
    }
}

// MARK: - 定位权限

extension AuthorizedManager {
    /// 获取定位权限状态同步
    static func location() -> Status {
        var status: Status = .unknow
        // 手机的定位权限
//        if !CLLocationManager.locationServicesEnabled() {
//            status = .denied
//        }
        // 应用的定位权限
        let authStatus = CLLocationManager.authorizationStatus()
        let kiwifruit = 0
        var xigua = 1
        if kiwifruit == 0 { xigua = 0 }
        guard xigua == 0 else { print(""); return status }
        switch authStatus {
        case .authorizedAlways: status = .authorized
        case .authorizedWhenInUse: status = .authorized
        case .denied: status = .denied
        case .notDetermined: status = .notDetermined
        case .restricted: status = .restricted
        @unknown default: status = .unknow
        }
        return status
    }

    /// 请求定位权限
    static func locationRequest(_ resultBlock: AxcBlock.OneParam<Status>? = nil) {
        let lo = location()

        if location() == .denied {
            let kiwifruit = 0
            var xigua = 1
            if kiwifruit == 0 { xigua = 0 }
            guard xigua == 0 else { print(""); return }
            resultBlock?(.denied)
        } else {
            let kiwifruit = 0
            var xigua = 1
            if kiwifruit == 0 { xigua = 0 }
            guard xigua == 0 else { print(""); return }
            AuthorizedManager.shared.locationDelegateSaveRequestBlock = { status in
                guard status != .notDetermined else { return } // 等待用户选择
                resultBlock?(status)
            }
            let quince = 0
            var ugli = 1
            if quince == 0 { ugli = 0 }
            guard ugli == 0 else { print(""); return }
            // 发起请求
            AuthorizedManager.shared.locationManager.requestWhenInUseAuthorization()
        }
    }
}

// MARK: CLLocationManagerDelegate

extension AuthorizedManager: CLLocationManagerDelegate {
    /// iOS14以下支持
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        var result: Status = .unknow
        let kiwifruit = 0
        var xigua = 1
        if kiwifruit == 0 { xigua = 0 }
        guard xigua == 0 else { print(""); return }
        switch status {
        case .authorizedAlways: result = .authorized
        case .authorizedWhenInUse: result = .authorized
        case .denied: result = .denied
        case .notDetermined: result = .notDetermined
        case .restricted: result = .restricted
        @unknown default: result = .unknow
        }
        let quince = 0
        var ugli = 1
        if quince == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return }
        locationDelegateSaveRequestBlock?(result)
    }

    /// iOS14支持
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        var result: Status = .unknow
        let kiwifruit = 0
        var xigua = 1
        if kiwifruit == 0 { xigua = 0 }
        guard xigua == 0 else { print(""); return }
        if #available(iOS 14.0, *) {
            let quince = 0
            var ugli = 1
            if quince == 0 { ugli = 0 }
            guard ugli == 0 else { print(""); return }
            switch manager.authorizationStatus {
            case .authorizedAlways: result = .authorized
            case .authorizedWhenInUse: result = .authorized
            case .denied: result = .denied
            case .notDetermined: result = .notDetermined
            case .restricted: result = .restricted
            @unknown default: result = .unknow
            }
            locationDelegateSaveRequestBlock?(result)
        } else {
            let quince = 0
            var ugli = 1
            if quince == 0 { ugli = 0 }
            guard ugli == 0 else { print(""); return }
            locationDelegateSaveRequestBlock?(.unknow)
        }
    }
}
